<template>
	<view class="container">
		<!-- 商品预览图 -->
		<image :src="product.image" mode="aspectFit" class="preview-image" @tap="previewImage(product.image)"></image>
		
		<!-- 基本信息 -->
		<view class="info-card">
			<view class="info-section-title">{{product.name}}</view>

			<view class="info-row">
				<text class="info-value">{{product.category}}</text>
			</view>
			<view class="info-row">
				<text class="info-value">{{product.date || '未设置'}}</text>
			</view>
			
			<!-- 珍珠信息 -->
			<view class="info-section-divider" v-if="hasPearlInfo"></view>
			<view class="info-section-title" v-if="hasPearlInfo">珍珠信息</view>
			<view v-if="hasPearlInfo">
				<view class="info-row">
					<text class="info-label light">珍珠尺寸</text>
					<text class="info-value">{{selectedSKU?.pearlSize ? selectedSKU.pearlSize + 'mm' : '未设置'}}</text>
				</view>
				<view class="info-row">
					<text class="info-label light">珍珠颜色</text>
					<text class="info-value">{{selectedSKU?.pearlColor || '未设置'}}</text>
				</view>
				<view class="info-row">
					<text class="info-label light">珍珠材质</text>
					<text class="info-value">{{product.pearlMaterial || '未设置'}}</text>
				</view>
			</view>
			
			<!-- 配件信息 -->
			<view class="info-section-divider"></view>
			<view class="info-section-title">配件信息</view>
			<view>
				<view class="info-row">
					<text class="info-label light">金属材质</text>
					<text class="info-value">{{product.metalMaterial || '未设置'}}</text>
				</view>
				<view class="info-row">
					<text class="info-label light">玉石尺寸</text>
					<text class="info-value">{{product.jadeSize ? product.jadeSize + 'mm' : '未设置'}}</text>
				</view>
				<view class="info-row">
					<text class="info-label light">玉石材质</text>
					<text class="info-value">{{product.jadeMaterial || '未设置'}}</text>
				</view>
				<view class="info-row">
					<text class="info-label light">其他配件</text>
					<text class="info-value">{{product.accessoryOthers || '未设置'}}</text>
				</view>
			</view>
		</view>
		
		<!-- 渠道信息 -->
		<view class="channel-section" v-if="product.channel && product.channel.length > 0">
			<view class="section-title">渠道信息</view>
			<view class="channel-list">
				<view class="channel-item" v-for="(channel, index) in product.channel" :key="index">
					<text class="channel-name">{{channel.name}}</text>
					<view class="channel-link-container" @tap="copyChannelLink(channel.link)">
						<text class="channel-link">{{channel.link}}</text>
						<text class="copy-hint">点击复制</text>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 备注信息 -->
		<view class="remark-section" v-if="product.remark">
			<view class="section-title">备注</view>
			<view class="remark-content">{{product.remark}}</view>
		</view>
		
		
		<!-- SKU列表 -->
		<view class="sku-section" v-if="product.skus && product.skus.length > 0">
			<view class="section-title">规格列表</view>
			<view class="sku-list">
				<view class="sku-item" v-for="(sku, index) in product.skus" :key="index">
					<view class="sku-header">
						<text class="sku-title">规格{{index + 1}}</text>
					</view>
					<view class="sku-content">
						<!-- 左侧：属性列表 -->
						<view class="sku-left-column">
							<view class="simple-row" v-if="sku.length">
								<text class="simple-label">整体长度:</text>
								<text class="simple-value">{{sku.length}}</text>
							</view>
							<view class="simple-row" v-if="sku.diameter">
								<text class="simple-label">佩戴直径:</text>
								<text class="simple-value">{{sku.diameter}}</text>
							</view>
							<view class="simple-row" v-if="sku.pearlSize">
								<text class="simple-label">珍珠尺寸:</text>
								<text class="simple-value">{{sku.pearlSize}}</text>
							</view>
							<view class="simple-row" v-if="sku.pearlColor">
								<text class="simple-label">珍珠颜色:</text>
								<text class="simple-value">{{sku.pearlColor}}</text>
							</view>
						</view>
						
						<!-- 右侧：SKU编号和价格 -->
						<view class="sku-right-column">
							<view class="simple-row">
								<text class="simple-label">编号:</text>
								<text class="simple-value">{{sku.skuCode || `SKU-${index+1}`}}</text>
							</view>
							<view class="simple-row">
								<text class="simple-label">标价:</text>
								<text class="simple-value list-price">¥{{sku.listPrice || '-'}}</text>
							</view>
							<view class="simple-row">
								<text class="simple-label">售价:</text>
								<text class="simple-value sale-price">¥{{sku.salePrice || '-'}}</text>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 底部操作栏 -->
		<view class="bottom-bar">
			<view class="bottom-divider"></view>
			<view class="bottom-btn-container">
				<button v-if="isStaff" class="bottom-btn edit" @tap="editProduct">编辑</button>
				<button v-if="isStaff" class="bottom-btn delete" @tap="deleteProduct">删除</button>
				<button class="bottom-btn share" open-type="share">分享</button>
				<button class="bottom-btn add-to-cart" @tap="addToCart">加入货盘</button>
			</view>
		</view>
	</view>
</template>

<script setup>
import auth from '../../utils/auth.js';
import { onShareAppMessage } from '@dcloudio/uni-app'
onShareAppMessage(() => {
  return { title: 'hello' }
})
// Removed onShareAppMessage implementation as it's moved to the methods section

</script>

<script>
	import { productApi, cartApi } from '../../api/index.js';
	
	import { userApi, orderApi } from '../../api/index.js';
	
	export default {
		data() {
			return {
				isStaff: false, // 默认为false
				skuCodeParam: '',
				selectedSKU: null,
				product: {
					id: '',
					name: '',
					category: '',
					price: '',
					image: '',
					warehouse: '',
					date: '',
					
					// 规格列表
					lengthList: [],
					diameterList: [],
					pearlSizeList: [],
					pearlColorList: [],
					
					// 珍珠属性
					pearlMaterial: '',
					pearlRoundness: '',
					pearlClarity: '',
					
					// 配件属性
					metalMaterial: '',
					jadeSize: '',
					jadeMaterial: '',
					accessoryOthers: '',
					
					// 渠道和备注
					channel: [],
					remark: '',
					
					// 直接传递SKU数据
					skus: []
				},
				isLoading: false
			}
		},
		computed: {
			hasPearlInfo() {
				return (
					this.selectedSKU?.pearlSize ||
					this.selectedSKU?.pearlColor ||
					this.product.pearlMaterial ||
					this.product.pearlRoundness ||
					this.product.pearlClarity
				);
			},
			combinedPearlInfo() {
				// 如果没有任何珍珠信息，返回默认文本
				if (!this.selectedSKU?.pearlSize && !this.selectedSKU?.pearlColor && 
					!this.product.pearlMaterial && !this.product.pearlRoundness && 
					!this.product.pearlClarity) {
					return '无珍珠信息';
				}
				

				// 按照"尺寸+颜色+材质，圆度，净度"的格式组合信息
				let result = '';
				
				// 第一部分：尺寸+颜色+材质
				let firstPart = [];
				if (this.selectedSKU?.pearlSize) {
					firstPart.push(this.selectedSKU.pearlSize + 'mm');
				}
				if (this.selectedSKU?.pearlColor) {
					firstPart.push(this.selectedSKU.pearlColor);
				}
				if (this.product.pearlMaterial) {
					firstPart.push(this.product.pearlMaterial);
				}
				result = firstPart.join('');
				
				// 第二部分：圆度
				if (this.product.pearlRoundness) {
					result += '，' + this.product.pearlRoundness;
				}
				
				// 第三部分：净度
				if (this.product.pearlClarity) {
					result += '，' + this.product.pearlClarity;
				}
				
				return result;
			},
			combinedAccessoryInfo() {
				const metal = this.product.metalMaterial || '未设置';
				let jade = '';
				if (this.product.jadeSize || this.product.jadeMaterial) {
					jade = (this.product.jadeSize ? this.product.jadeSize : '')+'mm' + (this.product.jadeMaterial ? this.product.jadeMaterial : '');
					if (!jade) jade = '无配石';
				} else {
					jade = '无配石';
				}
				const others = this.product.accessoryOthers || '无配件';
				return metal + '，' + jade + '，' + others;
			}
		},
		onShow() {
			auth.checkLogin();
		},
		onLoad(options) {
			auth.checkLogin();
			// 从列表页接收管理权限参数
			if (options.isStaff) {
				this.isStaff = options.isStaff === 'true';
			} else {
				// 如果没有传递参数，自行检查权限
				this.checkUserRole();
			}
			
			// 根据id获取商品详情
			if (options.id) {
				this.skuCodeParam = options.skucode || '';
				this.getProductDetail(options.id);
			} else {
				uni.showToast({
					title: '商品ID不存在',
					icon: 'none',
					success: () => {
						setTimeout(() => {
							uni.navigateBack();
						}, 1500);
					}
				});
			}
		},
		onShareAppMessage() {
			// 分享到微信聊天
			console.log('Sharing product:', this.product.id);
			
			// 确保有可分享的图片
			let imageUrl = this.product.image;
			// 如果没有主图，尝试使用第一个SKU的图片
			if (!imageUrl && this.product.skus && this.product.skus.length > 0 && this.product.skus[0].image) {
				imageUrl = this.product.skus[0].image;
			}
			
			return {
				title: this.product.name || '精美珠宝商品',
				path: `/pages/product/detail?id=${this.product.id}${this.skuCodeParam ? '&skucode=' + this.skuCodeParam : ''}`,
				imageUrl: imageUrl || '/static/share-default.png',
				success: () => {
					uni.showToast({
						title: '分享成功',
						icon: 'success'
					});
				},
				fail: () => {  
					uni.showToast({  
						title: '分享失败',  
						icon: 'none'  
					});
				}  
			};
		},
		methods: {
			// 检查用户角色并设置权限
			async checkUserRole() {
				try {
					
					const res = await userApi.getUserInfo();
					if (res && res.data) {
						this.isLogin = true;
						this.userInfo = res.data;
						// 更新本地存储
						uni.setStorageSync('userInfo', res.data);
					} else {
						this.isLogin = false;
						this.userInfo = {};
					}
					

					// 获取本地存储的用户信息
					const userInfo = uni.getStorageSync('userInfo');
					
					// 判断用户是否为admin或employee
					if (userInfo && (userInfo.role === 'admin' || userInfo.role === 'employee')) {
						this.isStaff = true;
					} else {
						this.isStaff = false;
					}
					console.log('详情页-当前用户角色:', userInfo ? userInfo.role : '未登录', '是否有管理权限:', this.isStaff);
				} catch (error) {
					console.error('获取用户角色失败', error);
					this.isStaff = false;
				}
			},
			async getProductDetail(id) {
				this.isLoading = true;
				uni.showLoading({ title: '加载中...' });
				
				try {
					const result = await productApi.getProductDetail(id);

					if (!result || !result.data) {
						throw new Error('获取商品数据失败');
					}
					
					const productData = result.data;

					console.log(productData)
					
					// 扁平化处理产品数据，确保我们的视图可以显示所有信息
					this.product = {
						id: id,
						name: productData.name || '',
						category: productData.category || '',
						image: productData.preview_image_url || '',
						warehouse: productData.warehouse || '',
						date: productData.date || '',
						
						// 从商品SKU中提取规格列表
						lengthList: this.extractUniqueValues(productData.skus, 'length'),
						diameterList: this.extractUniqueValues(productData.skus, 'diameter'),
						pearlSizeList: this.extractUniqueValues(productData.skus, 'pearlSize'),
						pearlColorList: this.extractUniqueValues(productData.skus, 'pearlColor'),
						
						// 珍珠属性
						pearlMaterial: productData.pearlMaterial || '',
						pearlRoundness: productData.pearlRoundness || '',
						pearlClarity: productData.pearlClarity || '',
						
						// 配件属性
						metalMaterial: productData.metalMaterial || '',
						jadeSize: productData.jadeSize || '',
						jadeMaterial: productData.jadeMaterial || '',
						accessoryOthers: productData.accessoryOthers || '',
						
						// 渠道和备注
						channel: productData.channel || [],
						remark: productData.remark || '',
						
						// 直接传递SKU数据
						skus: productData.skus || [],
						price: productData.price || ''
					};
					
					// 设置选中SKU
					if (this.product.skus && this.product.skus.length > 0) {
						if (this.skuCodeParam) {
							// 如果有传入skucode，则匹配对应的SKU
							this.selectedSKU = this.product.skus.find(sku => sku.skuCode === this.skuCodeParam);
							if (!this.selectedSKU) {
								// 如果找不到匹配的SKU，则使用第一个SKU
								this.selectedSKU = this.product.skus[0];
								this.skuCodeParam = this.selectedSKU.skuCode;
							}
						} else {
							// 如果没有传入skucode，则使用第一个SKU
							this.selectedSKU = this.product.skus[0];
							this.skuCodeParam = this.selectedSKU.skuCode;
						}
					}

					uni.hideLoading();
					this.isLoading = false;
				} catch (error) {
					console.error('获取商品详情失败', error);
					uni.hideLoading();
					this.isLoading = false;
					
					uni.showToast({
						title: '获取商品详情失败',
						icon: 'none',
						success: () => {
							setTimeout(() => {
								uni.navigateBack();
							}, 1500);
						}
					});
				}
			},
			// 从SKU数组中提取唯一值
			extractUniqueValues(skus, property) {
				if (!skus || !Array.isArray(skus)) return [];
				
				const values = skus
					.map(sku => sku[property])
					.filter(value => value && value.trim() !== '');
				
				// 去重
				return [...new Set(values)];
			},
			async addToCart() {
				if (this.isLoading) return;
				this.isLoading = true;
				
				try {
					uni.showLoading({ title: '添加中...' });
					
					// 使用选定的SKU ID（如果有）
					const params = {
						productId: this.product.id,
						quantity: 1  // 固定数量为1
					};
					
					// 如果有选定的SKU，则传递skuCode
					if (this.selectedSKU && this.selectedSKU.skuCode) {
						params.skuCode = this.selectedSKU.skuCode;
					} else if (this.product.skus && this.product.skus.length > 0) {
						// 如果没有选定SKU但有SKU列表，默认使用第一个SKU
						params.skuCode = this.product.skus[0].skuCode;
					}
					
					await cartApi.addToCart(params);
					
					uni.hideLoading();
					this.isLoading = false;
					
					uni.showToast({
						title: '已加入货盘',
						icon: 'success'
					});
				} catch (error) {
					console.error('添加购物车失败', error);
					uni.hideLoading();
					this.isLoading = false;
					
					uni.showToast({
						title: error.message || '添加失败',
						icon: 'none'
					});
				}
			},
			// 跳转到货盘页面
			gotoCart() {
				uni.switchTab({
					url: '/pages/cart/cart'
				});
			},
			// 编辑商品 - 添加权限检查
			editProduct() {
				if (!this.isStaff) {
					uni.showToast({
						title: '您没有权限执行此操作',
						icon: 'none'
					});
					return;
				}
				
				uni.navigateTo({
					url: `/pages/product/edit?id=${this.product.id}`
				});
			},
			// 添加图片预览功能
			previewImage(url) {
				if (!url) return;
				
				uni.previewImage({
					urls: [url],
					current: url,
					indicator: 'number',
					loop: false,
					longPressActions: {
						itemList: ['保存图片', '收藏'],
						success: function(data) {
							console.log('选中了第' + (data.tapIndex + 1) + '个按钮');
						},
						fail: function(err) {
							console.log(err);
						}
					}
				});
			},
			// 复制渠道链接到剪贴板
			copyChannelLink(link) {
				if (!link || typeof link !== 'string' || link.trim() === '') {
					uni.showToast({
						title: '链接为空，无法复制',
						icon: 'none',
						duration: 1500
					});
					return;
				}
				
				uni.setClipboardData({
					data: link.trim(),
					success: () => {
						uni.showToast({
							title: '链接已复制',
							icon: 'success',
							duration: 1500
						});
						
						// 可以在这里添加分析统计
						console.log('用户复制了链接:', link);
					},
					fail: (err) => {
						console.error('复制链接失败:', err);
						uni.showToast({
							title: '复制失败，请手动复制',
							icon: 'none',
							duration: 2000
						});
					}
				});
			},
			// 删除商品
			deleteProduct() {
				if (!this.isStaff) {
					uni.showToast({
						title: '您没有权限执行此操作',
						icon: 'none'
					});
					return;
				}
				
				// 显示确认对话框
				uni.showModal({
					title: '确认删除',
					content: '确定要删除该商品吗？此操作不可恢复。',
					confirmColor: '#dcc8a5',
					success: async (res) => {
						if (res.confirm) {
							try {
								uni.showLoading({ title: '删除中...' });
								
								// 调用API删除商品
								await productApi.deleteProduct(this.product.id);
								
								uni.hideLoading();
								uni.showToast({
									title: '删除成功',
									icon: 'success',
									duration: 1500,
									success: () => {
										// 删除成功后返回上一页
										setTimeout(() => {
											uni.navigateBack();
										}, 1500);
									}
								});
							} catch (error) {
								uni.hideLoading();
								console.error('删除商品失败', error);
								uni.showToast({
									title: error.message || '删除失败',
									icon: 'none',
									duration: 2000
								});
							}
						}
					}
				});
			}
		}
	}
</script>

<style>
	.container {
		min-height: 100vh;
		background-color: #f5f5f5;
		padding-bottom: 120rpx;
	}
	
	.preview-image {
		width: 100%;
		height: 500rpx;
	}
	
	/* 新的信息卡片样式 */
	.info-card {
		background-color: #fff;
		padding: 30rpx;
		margin-bottom: 20rpx;
	}
	
	.info-row {
		display: flex;
		margin-bottom: 2rpx;
		position: relative;
	}
	
	.info-label {
		color: #333;
		width: 180rpx;
		font-family: Light;
	}
	
	.info-label.light {
		color: #999;
		font-family: Light;
	}
	
	.info-value {
		color: #333;
		flex: 1;	
		font-family: Light;
	}
	
	.info-section-divider {
		height: 1rpx;
		margin: 20rpx 0;
	}
	
	.info-section-title {
		font-family: Regular;
		color: #333;
		margin: 2rpx 0;
	}
	
	.channel-section,
	.remark-section,
	.sku-section {
		background-color: #fff;
		padding: 30rpx;
		margin-bottom: 20rpx;
	}
	
	.section-title {
		font-size: 32rpx;
		color: #333;
		font-weight: bold;
		margin-bottom: 20rpx;
	}
	
	.channel-list {
		display: flex;
		flex-direction: column;
		gap: 15rpx;
	}
	
	.channel-item {
		background-color: #f9f9f9;
		padding: 15rpx 20rpx;
		border-radius: 8rpx;
		margin-bottom: 12rpx;
	}
	
	.channel-name {
		font-size: 28rpx;
		color: #333;
		font-weight: bold;
		display: block;
		margin-bottom: 5rpx;
	}
	
	.channel-link-container {
		display: flex;
		align-items: center;
		padding: 8rpx 0;
		background-color: rgba(243, 178, 80, 0.05);
		border-radius: 6rpx;
		transition: all 0.2s ease;
	}
	
	.channel-link-container:active {
		background-color: rgba(243, 178, 80, 0.15);
		transform: translateY(1rpx);
	}
	
	.channel-link {
		font-size: 24rpx;
		color: #F3B250;
		flex: 1;
		padding: 0 8rpx;
		word-break: break-all;
	}
	
	.copy-icon {
		font-size: 24rpx;
		margin: 0 8rpx;
		color: #F3B250;
	}
	
	.copy-hint {
		font-size: 22rpx;
		color: #999;
		margin-right: 10rpx;
	}
	
	.remark-content {
		font-size: 28rpx;
		color: #666;
		line-height: 1.6;
	}
	
	/* 新的底部按钮样式 */
	.bottom-bar {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: #fff;
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
	}
	
	.bottom-divider {
		height: 1rpx;
		background-color: #eee;
		width: 100%;
	}
	
	.bottom-btn-container {
		display: flex;
		height: 90rpx;
		background-color: #fff;
		align-items: center;
		padding: 0 10rpx;
	}
	
	.bottom-btn {
		flex: 1;
		height: 50rpx;
		line-height: 50rpx;
		text-align: center;
		display: flex;
		justify-content: center;
		align-items: center;
		margin: 0 15rpx;
		font-size: 28rpx;
		font-family: Regular;
	}
	
	.bottom-btn.edit {
		color: #282828;
		background-color: #fff;
		border: 1rpx solid #fff;
	}
	
	.bottom-btn.delete {
		color: #282828;
		background-color: #fff;
		border: 1rpx solid #fff;
	}
	
	.bottom-btn.share {
		color: #282828;
		background-color: #fff;
		border: 4rpx solid #dcc8a5;
		border-radius: 0rpx;
	}
	.bottom-btn::after{
		border: none;
	}
	
	.bottom-btn.add-to-cart {
		color: #FFF;
		background-color: #282828;
		border: 4rpx solid #dcc8a5;
		border-radius: 0rpx;
		padding: 0 20rpx;
		max-width: 220rpx;
		white-space: nowrap;
		overflow: visible;
	}
	
	/* 新版SKU样式 */
	.sku-section {
		background-color: #fff;
		padding: 30rpx;
		margin-bottom: 20rpx;
	}
	
	.sku-list {
		display: flex;
		flex-direction: column;
	}
	
	.sku-item {
		margin-bottom: 30rpx;
		background-color: #fff;
	}
	
	.sku-header {
		margin-bottom: 20rpx;
	}
	
	.sku-title {
		font-size: 30rpx;
		color: #333;
		font-weight: bold;
		font-family: Regular;
	}
	
	.sku-content {
		display: flex;
	}
	
	.sku-left-column {
		flex: 1;

	}
	
	.sku-right-column {
		flex: 1;
		
	}
	
	.simple-row {
		display: flex;
		margin-bottom: 14rpx;
		font-family: Light;
	}
	
	.simple-label {
		color: #666;
		font-size: 28rpx;
		font-family: Light;
	}
	
	.simple-value {
		color: #282828;
		margin-left: 50rpx;
		font-size: 28rpx;
		font-family: Light;
	}
	
	.list-price {
		color: #999;
		text-decoration: line-through;
	}
	
	.sale-price {
		color: #dcc8a5;
		font-family: Regular;
	}
</style> 